<template>
  <div style="height: 100%; width: 100%; overflow-x: auto;">

    <el-form :model="form" label-width="100px" inline>
      <el-form-item label="住院号" prop="hospitalNumber">
        <el-input v-model="form.hospitalNumber" placeholder="请输入住院号" style="width: 120px;" clearable 
    @clear="clearHospitalNumber" />
      </el-form-item>

      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="form.idCard" placeholder="请输入身份证号" clearable 
    @clear="clearIdCard" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="周期间隔" prop="cycleInterval">
        <el-input v-model="form.cycleInterval" placeholder="请输入周期间隔" clearable 
    @clear="clearCycleInterval" style="width: 120px;"/>
      </el-form-item>
      <el-form-item label="设定日期" prop="limitInterval">
        <el-input v-model="form.limitInterval" placeholder="请输入设定日期" clearable 
    @clear="clearLimitInterval" style="width: 120px;"/>
      </el-form-item>

      <el-form-item label="是否超出间隔" prop="gender">
        <el-select v-model="form.ifBeyondInterval" placeholder="请选择是否超出间隔" style="width: 120px;">
          <el-option label="全部" value="全部" />
          <el-option label="是" value="是" />
          <el-option label="否" value="否" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
        :key="tableKey"
        :data="nurseInfo"
        border
        style="width: 100%;"
        :height="tableHeight"
        :row-style="{ height: '50px' }"
        :cell-style="{ padding: '0' }">
      <el-table-column
          v-for="(column, index) in columns"
          :key="index"
          :prop="column.prop"
          :label="column.label"
          :min-width="column.minWidth">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          min-width="120px">
        <template v-slot:default="scope">
          <el-button @click="changeLimitInterval(scope.row)" type="text" size="medium">修改周期</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top: 10px;">
      <el-col :span="18">
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>

  <el-dialog
      v-model="limitIntervalDialogVisible"
      title="设定周期"
      width="500px"
      :before-close="handleClose"
    >
      <!-- 输入框 -->
      <el-form :model="changeForm" label-width="100px">
        <el-form-item label="周期天数" required>
          <el-input
            v-model.number="changeForm.cycleDays"
            type="number"
            placeholder="请输入周期天数"
            clearable
          />
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="limitIntervalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script>
import { apiClient } from '../api/apiClient' // 引入 apiClient 实例
import { ElMessageBox, ElMessage } from 'element-plus'

export default {
  name: 'RevisitRemind',
  data() {
    return {
      form: {
        hospitalNumber: "全部",
        idCard: "全部",
        cycleInterval: "全部",
            limitInterval: "全部",
            ifBeyondInterval:"全部"
      },
      changeForm: {
        cycleDays:''
      },
      submitting:false,
      selectedRow:null,
      limitIntervalDialogVisible:false,
      tableKey: 0,
      selectedIds: new Set(), // 全局存储选中的id
      exportDialogVisible: false,
      startTime: '',
      endTime: '',
      page: 1, // 当前页码
      size: 10, // 每页显示的记录数
      total: 0, // 总记录数
      allNurseInfo: [], // 用于存储从后端获取的所有数据
      nurseInfo: [], // 用于存储当前页的数据
      tableHeight: 'calc(100% - 50px)', // 计算表格高度，减去分页组件的高度
      columns: [ // 定义表格列
        { prop: 'hospitalNumber', label: '住院号', minWidth: '100px' },
        { prop: 'idCard', label: '身份证号', minWidth: '120px' },
        { prop: 'cycleInterval', label: '周期间隔', minWidth: '120px' },
        { prop: 'limitInterval', label: '设定日期', minWidth: '120px' },
        { prop: 'ifBeyondInterval', label: '是否超出周期', minWidth: '160px' },
      ]
    };
  },
  created() {
    this.fetchData();
  },
    methods: {
        clearHospitalNumber() {
            this.form.hospitalNumber = '全部'
         },
        clearIdCard() { 
            this.form.idCard = '全部'
        },
        clearCycleInterval() {
            this.form.cycleInterval = '全部'
         },
        clearLimitInterval() { 
            this.form.limitInterval = '全部'
      },
      changeLimitInterval(row) {
        this.selectedRow = row
          this.limitIntervalDialogVisible = true
      },
      async handleSubmit() {
          if (!this.changeForm.cycleDays || this.changeForm.cycleDays <= 0) {
            ElMessage.warning('请输入有效的周期天数')
            return
          }

          try {
            await ElMessageBox.confirm(
              `您确定要设置周期为 ${this.changeForm.cycleDays} 天吗?`,
              '确认设置',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
            
            this.submitting = true
            
            const response = await apiClient.post('/doctor/changePatientInterval', {
              hospitalNumber: this.selectedRow.hospitalNumber,
              newInterval:this.changeForm.cycleDays
            },
              {
                headers: { 'Content-Type': 'application/json' }
              })
            if (response.data.code === 1) {
              ElMessage.success('周期设置成功')
              this.selectedRow.limitInterval = this.changeForm.cycleDays
              if (this.selectedRow.ifBeyondInterval !== '未知') {
                this.selectedRow.ifBeyondInterval = this.selectedRow.cycleInterval >= this.selectedRow.limitInterval ? '是' : '否'
              }
            } else {
              ElMessage.error("设置失败")
            }
            this.limitIntervalDialogVisible = false
          } catch (error) {
            if (error !== 'cancel') { // 用户点击取消的情况
              console.error('设置失败:', error)
              ElMessage.error('设置失败，请重试')
            } else {
              ElMessage.info('已取消设置')
            }
          } finally {
            this.submitting = false
          }
      },
      isPositiveInteger(input) {
        const num = Number(input);
        return Number.isInteger(num) && num >= 0;
      },

    fetchData() {
      console.log("从后端凋数据")
      if (this.form.cycleInterval !== '全部' && !this.isPositiveInteger(this.form.cycleInterval)) {
        ElMessage.error("周期间隔必须是全部或者自然数")
        return
      }
      if (this.form.limitInterval !== '全部' && !this.isPositiveInteger(this.form.limitInterval)) {
        ElMessage.error("设置周期必须是全部或者自然数")
        return
      }
          const params = {
        authority:localStorage.getItem("authority"),
              hospitalNumber: this.form.hospitalNumber,
        idCard: this.form.idCard,
        cycleInterval: this.form.cycleInterval,  // 修正这里之前错误的hospitalNumber
        limitInterval: this.form.limitInterval, // 处理可能为空的日期
        ifBeyondInterval: this.form.ifBeyondInterval
      };
      //this.$message.info('正在加载数据...');
      apiClient.get('doctor/getCycleRemindInfo', { params }
      )
          .then(response => {
              if (response.data.code === 1) {
                console.log(response)
              this.allNurseInfo = response.data.data.map(item => ({
                ...item,
                id: item.id // 确保后端返回了id
              }));
              this.total = this.allNurseInfo.length; // 更新总记录数
              this.getTableData(); // 初始化表格数据
              //this.$message.success('数据加载成功');
            } else {
              console.error('Failed to fetch return visit list:', response.data.msg);
              this.$message.error('获取数据失败，请稍后重试');
            }
          })
          .catch(error => {
            console.error('Failed to fetch return visit list:', error);
            this.$message.error('网络请求失败，请稍后重试');
          });
    },
    handleClick(row) {
      console.log('Row clicked:', row);
      // 示例：弹窗显示详细信息
      this.$alert(JSON.stringify(row, null, 2), '详细信息', {
        dangerouslyUseHTMLString: true
      });
    },
    getTableData() {
      this.nurseInfo = this.allNurseInfo.slice((this.page - 1) * this.size, this.page * this.size);
      console.log('Current page data:', this.nurseInfo);
      this.tableKey++;
    },
    sizeChange(newSize) {
      this.size = newSize;
      this.getTableData();
    },
    currentChange(newPage) {
      this.page = newPage;
      this.getTableData();
    }
  }
};
</script>

<style scoped>
h1 {
  margin-bottom: 20px;
}
.el-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
</style>